<?php

Raise::load('core.RaiseStaticClass');
Raise::load('core.collection.RaiseCollection');
Raise::load('core.helper.config.RaiseSettings');
Raise::load('core.io.file.RaisePath');

/**
 * RaiseMime class
 * retrieves MIME and file extensions based on the mime.ini register
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.core.io
 * @since 1.2
 */
class RaiseMime extends RaiseStaticClass {
    
    /**
     * Collection of MIME entries
     * @var RaiseCollection
     * @static
     */
    private static $mime;

    /**
     * Caching the query of entries
     * @var RaiseCollection
     * @static
     */
    private static $cache;

    /**
     * Load the MIME types from the file
     * @static
     */
    private static function load(){
        if(!(self::$mime instanceof RaiseCollection)){
            $settings = new RaiseSettings(RaisePath::combine(RaisePath::phpRaisePath(), 'mime.ini'));
            self::$mime = $settings->get('mime');
            if(!self::$mime){
                self::$mime = new RaiseCollection();
            }
            self::$cache = new RaiseCollection();
        }
    }

    /**
     * Get the possible MIME types based on a file extension
     * @param string $extension
     * @return RaiseCollection
     * @static
     */
    public static function mime($extension){
        self::load();
        if(self::$cache->keyExists($extension)){
            return self::$cache->get($extension);
        }
        $a = self::$mime->get($extension);
        $a = new RaiseCollection($a);
        self::$cache->add($extension, $a);
        return $a;
    }

    /**
     * Get the file extensions of a specific type of MIME type
     * @param string $mime
     * @return RaiseCollection
     * @static
     */
    public static function extension($mime){
        self::load();
        $mime = strtolower($mime);
        $n = new RaiseCollection();
        if(self::$cache->keyExists($mime)){
            return self::$cache->get($mime);
        }
        foreach(self::$mime as $k => $i){
            $i = new RaiseCollection($i);
            if($i->indexOf($mime) !== null){
                $n->add($k);
            }
            unset($i);
        }
        self::$cache->add($mime, $n);
        return $n;
    }

}

